package cn.acewill.yxd.yunxundian.ui.schedule;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jimmy.common.listener.OnTaskFinishedListener;

import org.xutils.DbManager;
import org.xutils.ex.DbException;
import org.xutils.x;

import java.io.IOException;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

import cn.acewill.yxd.yunxundian.BaseActivity;
import cn.acewill.yxd.yunxundian.R;
import cn.acewill.yxd.yunxundian.YXDAPP;
import cn.acewill.yxd.yunxundian.adapter.TaskRecycleAdapter;
import cn.acewill.yxd.yunxundian.componet.CheckDataDialog;
import cn.acewill.yxd.yunxundian.componet.menology.OnCalendarClickListener;
import cn.acewill.yxd.yunxundian.componet.menology.schedule.ScheduleLayout;
import cn.acewill.yxd.yunxundian.componet.menology.schedule.ScheduleRecyclerView;
import cn.acewill.yxd.yunxundian.model.CommonMapBean;
import cn.acewill.yxd.yunxundian.model.Schedule;
import cn.acewill.yxd.yunxundian.model.tempLostRR;
import cn.acewill.yxd.yunxundian.pubClass.AsynData;
import cn.acewill.yxd.yunxundian.pubClass.MonPickerDialog;
import cn.acewill.yxd.yunxundian.pubClass.OkHttpManger;
import cn.acewill.yxd.yunxundian.pubClass.pubClass;
import cn.acewill.yxd.yunxundian.pubClass.signuppanel;
import cn.acewill.yxd.yunxundian.ui.MainActivity;
import cn.acewill.yxd.yunxundian.ui.sign.EditEvaluationActivity;
import cn.acewill.yxd.yunxundian.ui.sign.LookEvaDetialActivity;
import cn.acewill.yxd.yunxundian.ui.sign.SendMailActivity;
import cn.acewill.yxd.yunxundian.ui.sign.SignActivity;
import cn.acewill.yxd.yunxundian.ui.sign.WrittingEvaluationListActivity;
import cn.acewill.yxd.yunxundian.utils.CacheActivity;
import cn.acewill.yxd.yunxundian.utils.TopDialogUtils;


public class ScheduleActivity extends BaseActivity implements View.OnClickListener,OnTaskFinishedListener<List<Schedule>>{


    protected  YXDAPP yxdapp=new YXDAPP();
    protected  DbManager db = x.getDb(yxdapp.getDaoConfig());
    private ScheduleLayout slSchedule;
    private TextView currentMonth,currentDay,currentYear;
    private  int thisyear,thismonth,thisday;
    private String sYear,sMonth;
    private  TaskRecycleAdapter adapter;
    private ScheduleRecyclerView rvScheduleList;
    private RelativeLayout rlNoTask;
    private Dialog dialog;
    private AsynData ad=new AsynData(null);
    private int userId;
    //刷新数据的广播
    private BroadcastReceiver receiver;
    public static String refresh_Schedule = "Refresh_Schedule";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        View myview = LayoutInflater.from(this).inflate(R.layout.fragment_test, (ViewGroup) getWindow().getDecorView(),false);
        setContentView(myview);
        super.onCreate(savedInstanceState);
        initView();
        CacheActivity.addActivity(this);
        initRecycleView();
        LoadScheduleData();
        //注册广播
        IntentFilter filter=new IntentFilter();

        filter.addAction(refresh_Schedule);
        if (receiver==null){
            receiver=new refreshSsl();
            registerReceiver(receiver,filter);
        }
    }

    public void initView(){
        this.userId= MainActivity.id;
        Button moreBtn = (Button) findViewById(R.id.MoreBtn);
        ImageView iv = (ImageView) findViewById(R.id.backBtn);
        iv.setOnClickListener(this);
        moreBtn.setOnClickListener(this);

        LinearLayoutCompat addLinear = (LinearLayoutCompat) findViewById(R.id.addLinear);
        addLinear.setOnClickListener(this);
        rlNoTask= (RelativeLayout) findViewById(R.id.rlNoTask);
        this.slSchedule= (ScheduleLayout) findViewById(R.id.slSchedule);
        slSchedule.getMonthCalendar().setTodayToView();
        this.currentDay= (TextView) findViewById(R.id.currentDay);
        this.currentMonth= (TextView) findViewById(R.id.currentMonth);
        this.currentYear= (TextView) findViewById(R.id.currentYear);
        getCurrentdate();
        slSchedule.setOnCalendarClickListener(new OnCalendarClickListener() {
            @Override
            public void onClickDate(int year, int month, int day) {
                thisyear=year;
                thisday=day;
                thismonth=month;
                currentMonth.setText(month+1+"月");
                currentDay.setText(day+"日");
                currentYear.setText(year+"年");
                LoadScheduleData();
                updateSchedule();
            }
            @Override
            public void onPageChange(int year, int month, int day) {
                thisyear=year;
                thisday=day;
                thismonth=month;
                currentMonth.setText(month+1+"月");
                currentDay.setText(day+"日");
                currentYear.setText(year+"年");
                LoadScheduleData();
                updateSchedule();
            }
        });
    }
    public void initRecycleView(){
        rvScheduleList = slSchedule.getSchedulerRecyclerView();
        LinearLayoutManager layoutManager = new LinearLayoutManager(this );
        rvScheduleList.setLayoutManager(layoutManager);
        layoutManager.setOrientation(OrientationHelper. VERTICAL);
        rvScheduleList.setAdapter(adapter);
    }

   class refreshSsl extends BroadcastReceiver{

       @Override
       public void onReceive(Context context, Intent intent) {
           //刷新数据的操作
           int date=intent.getIntExtra("result",0);
           if (date==1){
               LoadScheduleData();
               updateSchedule();
           }
       }
   }

    public void getCurrentdate() {
        Calendar c = Calendar.getInstance();
        thisyear = c.get(Calendar.YEAR);
        thismonth = c.get(Calendar.MONTH);
        thisday = c.get(Calendar.DAY_OF_MONTH);
        currentMonth.setText(thismonth + 1 + "月");
        currentDay.setText(thisday + "日");
        currentYear.setText(thisyear + "年");
    }

    public void LoadScheduleData() {
        String mm= String.valueOf(thismonth+1);
        String dd=String.valueOf(thisday);
        if(mm.length()==1)
        {
            mm="0"+mm;
        }
        if(dd.length()==1){
            dd="0"+dd;
        }
        try {
            List<Schedule> taskList = db.selector(Schedule.class).where("schStartTime", "like", thisyear + "-" + mm + "-" + dd + "%").and("toUserId", "=", MainActivity.id).orderBy("states").orderBy("schStartTime").findAll();
            if (taskList !=null&& taskList.size()!=0) {
                rvScheduleList.setVisibility(View.VISIBLE);
                rlNoTask.setVisibility(View.GONE);
                adapter = new TaskRecycleAdapter(this, taskList, new TaskRecycleAdapter.MyCallBackClickListener() {
                    @Override
                    public void lookClick(Schedule schedule, int positon) {
                        //查看评估
                        Intent in=new Intent(ScheduleActivity.this,LookEvaDetialActivity.class)
                                .putExtra("schid",schedule.getID());
                        startActivity(in);
                    }

                    @Override
                    public void submitClick(Schedule tag, int positon) {
                        //提交数据网络请求
                        final int schId=tag.getID();
                        try{
                            List<tempLostRR> rr=db.selector(tempLostRR.class).where("schId","=",schId).findAll();
                            Schedule thisSch=db.selector(Schedule.class).where("ID","=",schId+"").findFirst();
                            if(thisSch.getStates()>1) {
                            //    if (rr == null || rr.size() == 0) {
//                                    showMessageOKCancel(new DialogInterface.OnClickListener() {
//                                        @Override
//                                        public void onClick(DialogInterface dialog, int which) {
//                                            Intent in = new Intent(ScheduleActivity.this, SendMailActivity.class).putExtra("schId", schId);
//                                            startActivityForResult(in, 101);
//                                        }
//                                    });
//                                    //showToast("");
//                                } else {
//                                    Intent in = new Intent(ScheduleActivity.this, SendMailActivity.class).putExtra("schId", schId);
//                                    startActivityForResult(in, 101);
                              //  }
                                boolean[] falg = CheckDataDialog.getInstance(ScheduleActivity.this).checkDataComplete(schId);
                                if (falg!=null){
                                    showTipDialog(falg,schId);
                                }else{
                                    BaseActivity.showToast(ScheduleActivity.this,"数据错误");
                                }
                            }else{
                                BaseActivity.showAnimaDialog(ScheduleActivity.this,"请先执行任务");
                            }
                        }catch (DbException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void shopSignClick(Schedule tag, int positon) {
                        //跳转门店签字
                        Intent in=new Intent(ScheduleActivity.this,SignActivity.class);
                        in.putExtra("rrschid",tag.getID());
                        startActivity(in);
                    }
                    @Override
                    public void addinfoClick(Schedule tag, int positon) {
                        //编辑
                        Intent in=new Intent(ScheduleActivity.this,EditEvaluationActivity.class);
                        in.putExtra("schId",tag.getID());
                        startActivityForResult(in,100);
                    }
                    @Override
                    public void goDetailClick(Schedule tag, int position) { //修改日程
                        Intent in=new Intent(ScheduleActivity.this, ScheduleModifiActivity.class);
                        in.putExtra("schid",tag.getID());
                        startActivity(in);
                    }
                });
                rvScheduleList.setAdapter(adapter);
            }else{

                rlNoTask.setVisibility(View.VISIBLE);
                rvScheduleList.setVisibility(View.GONE);
            }
        }
        catch (DbException e){
        }
    }

    //提交提示
    private void showTipDialog(boolean[] need, final int schId){
        if (!need[0]&&!need[1]&&!need[2]){
            startActivity(new Intent(this,SendMailActivity.class).putExtra("schId",schId));
        }else{
            final Dialog dialog= new Dialog(this,R.style.mydialog);
            View view = LayoutInflater.from(this).inflate(R.layout.eva_check_dialog, (ViewGroup)getWindow().getDecorView(),false);
            TextView addFollow = view.findViewById(R.id.addFollow);
            TextView shopSign = view.findViewById(R.id.shopSign);
            TextView jiBenData = view.findViewById(R.id.jiBenData);
            TextView gotoSubmit = view.findViewById(R.id.gotoSubmit);
            gotoSubmit.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                    startActivityForResult(new Intent(ScheduleActivity.this,SendMailActivity.class)
                            .putExtra("schId",schId),101);
                }
            });
            TextView cancel_action = view.findViewById(R.id.cancel_action);
            cancel_action.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                    startActivity(new Intent(ScheduleActivity.this,EditEvaluationActivity.class).putExtra("schId",schId));
                }
            });
            if (!need[0]){
                addFollow.setVisibility(View.GONE);
            }
            if (!need[1]){
                shopSign.setVisibility(View.GONE);
            }
            if (!need[2]){
                jiBenData.setVisibility(View.GONE);
            }
            dialog.setContentView(view);
            dialog.setCancelable(true);
            dialog.show();
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.MoreBtn:
                dialog=new Dialog(this,R.style.BottomDialog);
                View view= LayoutInflater.from(this).inflate(R.layout.schedule_more_dialog, (ViewGroup) getWindow().getDecorView(),false);
                TopDialogUtils.showTopDialog(this,dialog,view,5);
                Button closedialog= (Button) view.findViewById(R.id.closeDialog);
                closedialog.setOnClickListener(this);
                TextView addOther= (TextView) view.findViewById(R.id.addOther);
                addOther.setOnClickListener(this);
                TextView projectTask= (TextView) view.findViewById(R.id.projectTask);
                projectTask.setOnClickListener(this);
                TextView copyTask= (TextView) view.findViewById(R.id.copyTask);
                TextView checkTask = (TextView) view.findViewById(R.id.checkTask);
                TextView mailSch = (TextView)view.findViewById(R.id.mailSchedule);
                mailSch.setOnClickListener(this);
                checkTask.setOnClickListener(this);
                copyTask.setOnClickListener(this);
                dialog.show();
                break;
            case R.id.closeDialog:
                dialog.dismiss();
                break;
            case R.id.addOther:
                Intent in1=new Intent(this,ScheduleAddOtherActivity.class);
                startActivityForResult(in1,102);
                dialog.dismiss();
                break;
            case R.id.addLinear://加入判断是否是OE的情况
                try {
                    CommonMapBean role = db.selector(CommonMapBean.class).where("ServerId","=",userId)
                            .and("cmType","=","role").findFirst();
                    if(role!=null){
                        //OE任务界面
                        if (role.getCmValue().equals("OE")){
                            startActivityForResult(new Intent(this,schAdd.class)
                                    .putExtra("year",thisyear).putExtra("month",thismonth)
                                    .putExtra("day",thisday),102);
                            //startActivityForResult(new Intent(this,schAddForOE.class),102);//edit by hezm oe也可以安排日程

                        }else{
                            startActivityForResult(new Intent(this,schAdd.class)
                                    .putExtra("year",thisyear).putExtra("month",thismonth)
                                    .putExtra("day",thisday),102);
                        }
                    }else{
                        startActivityForResult(new Intent(this,schAdd.class)
                                .putExtra("year",thisyear).putExtra("month",thismonth)
                                .putExtra("day",thisday),102);
                    }
                } catch (DbException e) {
                    e.printStackTrace();
                }
                break;
            case R.id.projectTask:
                Intent in2=new Intent(this,tuisongSchedule.class);
                startActivityForResult(in2,100);//稍后加入刷新操作
                dialog.dismiss();
                break;
            case R.id.copyTask:
                startActivityForResult(new Intent(this,CopyTaskActivity.class),102);
                dialog.dismiss();
                break;
            case R.id.backBtn:
                finish();
                break;
            case R.id.mailSchedule:
                dialog.dismiss();
                MonPickerDialog.OnDateSetListener listener1 = new MonPickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                        sYear = year+"";
                        if(month+1<10)
                        {
                            sMonth = "0"+(month+1);
                        }
                        else
                        {
                            sMonth = ""+(month+1);
                        }
                        checkCanMail();
                        //tvShowDialog.setText(sYear+"-"+sMonth);
                    }
                };
                MonPickerDialog mpd= new MonPickerDialog(this,listener1,thisyear,thismonth,thisday);
                mpd.setTitle("请选择年月");
                mpd.show();

                break;
            /*日程检验*/
            case R.id.checkTask:
                startActivityForResult(new Intent(this,ScheduleCheckTaskActivity.class),102);
                dialog.dismiss();
                break;
        }
    }


    //检查日程是否可以发送邮件

    public void checkCanMail(){
        if (sYear==null||sMonth==null){
            return;
        }
        HashMap<String,String> map = new HashMap<>();
        map.put("task","checkCanMail");
        map.put("empid",String.valueOf(MainActivity.id));
        map.put("year",sYear);
        map.put("month",sMonth);
        try {
            OkHttpManger.getInstance().postAsync(pubClass.Server_namehzm, new OkHttpManger.MyCallback() {
                @Override
                public void onSuccess(String result) {
                    String[] arry = result.split("\\|");
                    if (arry[0].equals("200")){
                        showToast(ScheduleActivity.this,"检验成功");
                        Intent in = new Intent(ScheduleActivity.this,ScheduleMailActivity.class);
                        in.putExtra("month",sMonth);
                        in.putExtra("year",sYear);
                        startActivity(in);
                    }else{
                        if (arry.length==4){
                            if (arry[1]!= null){
                                showToast(ScheduleActivity.this,arry[1]);
                            }
                        }else{
                            showToast(ScheduleActivity.this,"检验失败");
                        }
                    }
                }
                @Override
                public void onFailture() {
                    showToast(ScheduleActivity.this,"检验失败，请检查网络状态");
                }
            },map);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (resultCode) { //resultCode为回传的标记
            /*添加日程返回刷新页面*/
            case 101:
                ad.asynScheduleDataWithCallBack(MainActivity.id,new pubClass.MyCallBack<String>() {
                    @Override
                    public void onSuccess(String result) {
                        ad.asynScheduleData(result);
                        LoadScheduleData();
                        //adapter.notifyDataSetChanged();
//                        new Thread(new updateThread()).start();
                        //刷新页面
                        updateSchedule();
                    }
                });
                break;
            case 2001:
                LoadScheduleData();
                break;
            case 100:
            case 102:
                LoadScheduleData();
                updateSchedule();
                break;
            default:
                LoadScheduleData();
                updateSchedule();
                break;
        }
        if(requestCode==100||requestCode==101)
        {
            LoadScheduleData();
        }

    }
//    class updateThread implements Runnable{
//        @Override
//        public void run() {
//            while (!Thread.currentThread().isInterrupted()) {
//                Message msg=new Message();
//                msg.what=1;
//                mhandler.sendMessage(msg);
//                try {
//                    Thread.sleep(200);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//                Thread.currentThread().interrupt();
//            }
//        }
//    }
//    Handler mhandler=new Handler(){
//        @Override
//        public void handleMessage(Message msg) {
//            switch (msg.what){
//                case 1:
//                    com.jimmy.common.bean.Schedule schedule=new com.jimmy.common.bean.Schedule();
//                    setResult(103);
//                    finish();
//                    break;
//            }
//        }
//    };

    private void showMessageOKCancel(DialogInterface.OnClickListener okListener) {
        new AlertDialog.Builder(this)
                .setMessage("该评估表尚未填写任何失分项,是否提交？")
                .setPositiveButton("确定", okListener)
                .setNegativeButton("取消", null)
                .create()
                .show();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode==KeyEvent.KEYCODE_BACK){
            finish();
        }
        return false;
    }

    public void updateSchedule(){
        slSchedule.updateTask();
    }
    public void unregisterBroadCastReceiver(){
        unregisterReceiver(receiver);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterBroadCastReceiver();
    }

    @Override
    public void onTaskFinished(List<Schedule> data) {
        updateSchedule();
    }
}